package com.hwpt.chesedemo;

import android.util.Log;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RunWith(AndroidJUnit4.class)
public class QianwenTest {
    private static final String TAG = "QianwenTest";
    private static final String API_KEY = "sk-c0f76c2c02104d8e8590bbcdc1764db5"; // 替换为你的API密钥


    @Test
    public void testEmpty() {
        Log.d("QianwenTest", "空测试执行成功");
    }
    /**
     * 同步调用测试（基础功能，优先确保这个能跑通）
     */
    @Test
    public void testSyncCall() {
        try {
            // 初始化API Key（2.21.11版本专用方式）
            System.setProperty("dashscope.api.key", API_KEY);

            // 构建提示词模板
            List<Message> messages = new ArrayList<>();
            messages.add(Message.builder()
                    .role("system")  // 字符串参数，必须是"system"/"user"/"assistant"
                    .content("你是一个简洁的回答助手，只说一句话")
                    .build());
            messages.add(Message.builder()
                    .role("user")
                    .content("Android的四大组件是什么？")
                    .build());

            // 构建请求参数
            GenerationParam param = GenerationParam.builder()
                    .model("qwen-turbo")  // 确保已开通该模型权限
                    .messages(messages)
                    .build();

            // 同步调用
            Generation generation = new Generation();
            GenerationResult result = generation.call(param);  // 用call()而非asyncCall()

            // 解析结果
            if (result.getOutput() != null) {
                Log.d(TAG, "同步调用成功：" + result.getOutput().getText());
            } else {
                Log.e(TAG, "同步调用失败：" + result);
            }

        } catch (NoApiKeyException e) {
            Log.e(TAG, "API密钥错误：" + e.getMessage());
        } catch (ApiException e) {
            Log.e(TAG, "调用异常：" + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "其他错误：" + e.getMessage());
        }
    }

    /**
     * 模拟异步调用（用线程池执行同步方法，避免阻塞）
     */
    @Test
    public void testAsyncLikeCall() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        // 创建单线程池执行异步任务
        ExecutorService executor = Executors.newSingleThreadExecutor();

        executor.execute(() -> {
            try {
                System.setProperty("dashscope.api.key", API_KEY);

                List<Message> messages = new ArrayList<>();
                messages.add(Message.builder()
                        .role("user")
                        .content("什么是Java的多态？")
                        .build());

                GenerationParam param = GenerationParam.builder()
                        .model("qwen-turbo")
                        .messages(messages)
                        .build();

                Generation generation = new Generation();
                GenerationResult result = generation.call(param);  // 同步方法放在子线程执行

                if (result.getOutput() != null) {
                    Log.d(TAG, "模拟异步调用成功：" + result.getOutput().getText());
                } else {
                    Log.e(TAG, "模拟异步调用失败：" + result);
                }

            } catch (Exception e) {
                Log.e(TAG, "异步任务错误：" + e.getMessage());
            } finally {
                latch.countDown();
                executor.shutdown(); // 关闭线程池
            }
        });

        latch.await(); // 等待子线程完成
    }
}